﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Documents;
using System.Windows.Controls;

namespace Com.CodePlex.SPC3.ProfileImageUpload {

	public class WorkerMessage {
		public WorkerMessage(string message, System.Drawing.Color color) {
			this.Message = message;
			this.Color = color;
		}
		public string Message { get; private set; }
		public System.Drawing.Color Color { get; private set; }
	}

	public partial class MainWindow : Window {

		ProfileImageUploadManager manager = new ProfileImageUploadManager();

		public MainWindow() {
			InitializeComponent();
			txtSiteUrl.Text = Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.SiteUrl;
			txtUsername.Text = Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.Username;
			//txtPassword.Password = Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.Password;
			txtSourceDirectory.Text = Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.SourceDirectory;
			txtFilenameFormat.Text = Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.FilenameFormat;
            ddlAuthType.Text = Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.AuthType;
			AddMessage("Ready");
		}

		private void Exit(object sender, EventArgs e) {
			if (Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.SiteUrl != txtSiteUrl.Text ||
				Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.Username != txtUsername.Text ||
				//Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.Password != txtPassword.Password ||
				Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.SourceDirectory != txtSourceDirectory.Text ||
                Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.FilenameFormat != txtFilenameFormat.Text ||
                Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.AuthType != ddlAuthType.Text) {

				ExitDialog dlg = new ExitDialog();
				dlg.Owner = this;
				dlg.ShowDialog();
				if (!dlg.Result.HasValue) {
					if (e is System.ComponentModel.CancelEventArgs) {
						((System.ComponentModel.CancelEventArgs)e).Cancel = true;
					}
				} else {
					if (dlg.Result.Value) {
						Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.SiteUrl = txtSiteUrl.Text;
						Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.Username = txtUsername.Text;
						//Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.Password = txtPassword.Password;
						Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.SourceDirectory = txtSourceDirectory.Text;
						Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.FilenameFormat = txtFilenameFormat.Text;
                        Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.AuthType = ddlAuthType.Text;
						Com.CodePlex.SPC3.ProfileImageUpload.Properties.Settings.Default.Save();
					}
					Application.Current.Shutdown();
				}
			} else {
				if (e is System.ComponentModel.CancelEventArgs) {

				} else {
					Application.Current.Shutdown();
				}
			}
		}

		private void btnBrowse_Click(object sender, RoutedEventArgs e) {
			var dlg = new System.Windows.Forms.FolderBrowserDialog();
			dlg.SelectedPath = txtSourceDirectory.Text;
			dlg.ShowNewFolderButton = false;
			System.Windows.Forms.DialogResult result = dlg.ShowDialog(this.GetIWin32Window());
			if (result == System.Windows.Forms.DialogResult.OK) {
				txtSourceDirectory.Text = dlg.SelectedPath;
			}
		}

		private void btnExit_Click(object sender, RoutedEventArgs e) {
			Exit(sender, e);
		}

		private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
			Exit(sender, e);
		}

		private void AddMessage(string message) {
			AddMessage(new WorkerMessage(message, System.Drawing.Color.Black));
		}

		private void AddMessage(WorkerMessage message) {
			SolidColorBrush brush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(message.Color.A, message.Color.R, message.Color.G, message.Color.B));
			TextRange range = new TextRange(txtMessage.Document.ContentEnd, txtMessage.Document.ContentEnd);
			range.Text = DateTime.Now + ": " + message.Message + "\n";
			range.ApplyPropertyValue(TextElement.ForegroundProperty, brush);
			txtMessage.ScrollToEnd();
		}

		private void txtSiteUrl_Populating(object sender, PopulatingEventArgs e) {
			try {
				string text = txtSiteUrl.Text;
				var candidates = new List<string>();
				foreach (string url in new UrlHistoryDAO().GetItems(text).Take(10)) {
					candidates.Add(url);
				}
				txtSiteUrl.ItemsSource = candidates;
				txtSiteUrl.PopulateComplete();
			} catch (Exception ex) {
				int i = 0;
			}
		}

		private void btnUpload_Click(object sender0, RoutedEventArgs e0) {
			BackgroundWorker worker = new BackgroundWorker();
			worker.WorkerReportsProgress = true;
			worker.DoWork += delegate(object sender, DoWorkEventArgs e) {
                worker.ReportProgress(0, "Uploading");
                UploadArgs args = (UploadArgs)e.Argument;
                try {
                    ManagerResult result = manager.Validate(args, worker);
                    if (result.Success) {
                        result = manager.Process(args, worker);
                        if (result.Success) {

                        }
                    }
                    e.Result = result;
                } catch (Exception ex) {
                    worker.ReportProgress(0, new WorkerMessage("DoWork failed:", System.Drawing.Color.Red));
					worker.ReportProgress(0, new WorkerMessage(ex.ToString(), System.Drawing.Color.Red));
                }
			};
			worker.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e) {
				if (e.UserState is WorkerMessage) {
					AddMessage((WorkerMessage)e.UserState);
				} else {
					AddMessage((string)e.UserState);
				}
			};
			worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) {
                ManagerResult result = e.Result as ManagerResult;
				AddMessage("Done");
			};
			worker.RunWorkerAsync(new UploadArgs() {
				SiteUrl = txtSiteUrl.Text,
				Username = txtUsername.Text,
				Password = txtPassword.Password,
				SourceDirectory = txtSourceDirectory.Text,
				FilenameFormat = txtFilenameFormat.Text,
                AuthType = ddlAuthType.Text
			});
		}
	}
}
